<template>
  <div>
    <Drawer
      ref="modal"
      :title="`${editType === 'create' ? $t('staffIndex.staffDepartCreateAdd') : $t('staffIndex.staffDepartCreateEdit')}`"
      :width="500"
      :value="show"
      :beforeClose="$_modal_decideIfClose"
    >
    <!-- 体验版提示框 -->
      <Alert show-icon class="alertTit">
          <Icon type="ios-bulb-outline" slot="icon"></Icon>
          {{ $t("loginIndex.loginIpAddressVerser1") }}
      </Alert>
      <Form
        ref="form"
        :labelWidth="100"
        :model="formData"
        :rules="formRule"
      >
        <FormItem prop="username" :label="$t('staffIndex.staffDepartUsername')">
          <Input v-model="formData.username" :placeholder="$t('staffIndex.staffDepartUsernameInput')" />
        </FormItem>
        <FormItem prop="sex" :label="$t('staffIndex.staffDeparSex')">
          <RadioGroup
            v-model="formData.sex"
          >
            <Radio
              v-for="(item, idx) in sexs" :key="idx"
              :label="item.value"
            >{{ item.name }}</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem prop="file" :label="$t('staffIndex.staffDepartPhoto')">
          <div
            v-if="editType === 'update' && !ifSelFile"
            class="img"
          >
            <img style="width: 120px" :src="getPhoto(formData.photo)" >
          </div>
          <Upload
            v-model="formData.file"
            action="/"
            :before-upload="handleUpload"
            :format="['jpg','png']"
            :on-format-error="handleFormatError"
            :max-size="204800"
            :on-exceeded-size="handleMaxSize"
          >
            <Button icon="ios-cloud-upload-outline">{{ $t("staffIndex.staffDepartPhotoSel") }}</Button>
          </Upload>
          <span v-if="ifSelFile">{{ formData.file.name }}</span>
        </FormItem>
        <FormItem prop="worknum" :label="$t('staffIndex.staffDepartWorkNum')">
          <Input v-model="formData.worknum"  :placeholder="$t('staffIndex.staffDepartWorkNumInput')" />
        </FormItem>
        <FormItem prop="cardnum" :label="$t('staffIndex.staffDepartIDnumber')">
          <Input v-model="formData.cardnum" :placeholder="$t('staffIndex.staffDepartIDnumberInpue')" />
        </FormItem>
        <FormItem prop="cardNo" :label="$t('staffIndex.staffDepartICnum')">
          <Input maxlength="20" v-model="formData.cardNo" :placeholder="$t('staffIndex.staffDepartICnumberInpue')" />
        </FormItem>
        <FormItem prop="birthday" :label="$t('staffIndex.staffDepartBirthday')">
          <DatePicker
            v-model="formData.birthday"
            type="date"
            :placeholder="$t('staffIndex.staffDepartBirthdayInput')"
          />
        </FormItem>
        <FormItem prop="jointime" :label="$t('staffIndex.staffDepartEntrytTime')">
          <DatePicker
            v-model="formData.jointime"
            type="date"
            :placeholder="$t('staffIndex.staffDepartEntrytTimeInput')"
          />
        </FormItem>
        <FormItem class="glo-btn-group">
          <Button
            type="primary"
            :loading="loading"
            @click="handleSubmit"
          >{{ $t("devicesCreate.devCreateSubmit") }}</Button>
          <Button
            @click="$_modal_close"
          >{{ $t("devicesCreate.devCreateCancel") }}</Button>
        </FormItem>
      </Form>
    </Drawer>
  </div>
</template>

<script>
import {
  mapState,
} from 'vuex'
import _ from 'lodash'
import moment from 'moment'

import modalMixin from '@/utils/mixins/modalMixin.js'
import {
  create,
  update,
} from '@/api/person.js'
import {
  getPhoto,
} from '@/api/public.js'

const DEFAULT_FORM = {
  username: '',
  sex: '',
  file: '',
  worknum: '',
  cardnum: '',
  cardNo: '',
  birthday: '',
  jointime: '',
}

export default {
  mixins: [
    modalMixin,
  ],

  props: {
    editType: {
      type: String,
      default: 'create',
    },
    editItem: Object,
    parentDepart: [String, Number],
  },
  data () {
    return {
      sexs: [
        { name: this.$t('staffIndex.staffDepartMan'), value: '1' },
        { name: this.$t('staffIndex.staffDepartWoman'), value: '2' },
      ],
      formData: _.cloneDeep(DEFAULT_FORM),
      formRule: {
        username: { required: true, message: this.$t('staffIndex.staffDepartUsernameIn') },
        sex: { required: true, message: this.$t('staffIndex.staffDepartSexIn') },
        file: {
          required: true,
          validator: (rule, value, callback) => {
            console.log(this.formData)
            let errMsg
            if (
              (!this.formData.photo || this.formData.photo === '')
              && (!value || value === '')
            ) {
              errMsg = this.$t('staffIndex.staffDepartPhotoIn')
            }
            if (errMsg) {
              return callback(new Error(errMsg))
            }
            callback()
          },
        },
        cardnum: {
          validator: (rule, value, callback) => {
            const regIdCard = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
            let errMsg
            if (
              value
              && value !== ''
              && !regIdCard.test(value)
            ) {
              errMsg = this.$t('visitorsIndex.visitorsCardNum1')
            }
            if (errMsg) {
              return callback(new Error(errMsg))
            }
            callback()
          },
        },
      },
      oldPhoto:''
    }
  },
  computed: {
    ...mapState('depart', [
      'selectedDepart',
    ]),
    ifSelFile () {
      return typeof this.formData.file === 'object'
    },
  },

  mounted () {
    this.show = true
    if (this.editType === 'update') {
      const formData = {}
      const keys = Object.keys(DEFAULT_FORM)
      keys.forEach(key => {
        formData[key] = _.isUndefined(this.editItem[key])
          ? DEFAULT_FORM[key]
          : this.editItem[key]
      })
      formData.mid = this.editItem.mid
      formData.photo = this.editItem.photo
      this.oldPhoto=this.editItem.photo
      this.formData = _.cloneDeep(formData)
    }
  },

  methods: {
    getPhoto,
    handleUpload (file) {
      console.log(file)
      this.formData.file = file
      this.formData.photo = ''
      return false
    },
    handleFormatError (file) {
      console.log(123456)
      // this.$Notice.warning({
      //   title: this.$t('staffIndex.staffFormatSure'),
      //   desc: this.$t('versionIndex.verListFile') + file.name + this.$t('staffIndex.staffFormat'),
      // })
    },
    handleMaxSize (file) {
      console.log(666)

      // this.$Notice.warning({
      //   title: this.$t('staffIndex.staffSizeerror'),
      //   desc: this.$t('versionIndex.verListFile') + file.name + this.$t('staffIndex.staffMoreerror'),
      // })
    },
    async handleSubmit () {
      const ifVlid = await this.$refs.form.validate()
      if (ifVlid && this.editType === 'create') {
        this.handleCreate()
      }
      if (ifVlid && this.editType === 'update') {
        this.handleUpdate()
      }
    },

    generateFormData () {
      const data = _.cloneDeep(this.formData)
      data.depId = this.selectedDepart
      if (_.isDate(data.birthday)) {
        data.birthday = moment(data.birthday).format('YYYY-MM-DD')
      } else {
        data.birthday = ''
      }
      if (!data.worknum) {
        data.worknum = ''
      }
      if (_.isDate(data.jointime)) {
        data.jointime = moment(data.jointime).format('YYYY-MM-DD')
      } else {
        data.jointime = ''
      }
      if (!data.cardNo) {
        data.cardNo = ''
      }
      if (!data.cardnum) {
        data.cardnum = ''
      }
      
      if(this.editType === 'update'){
        console.log('handleUpdatecardnum',this.formData.cardNo,this.editItem.cardNo)
        if(this.formData.cardNo===this.editItem.cardNo){
          data.cardNoChanged=0
        }else{
          data.cardNoChanged=1
        }
      }
      const formData = new FormData()
      const keys = Object.keys(data)
      for (let i = 0; i < keys.length; i += 1) {
        const key = keys[i]
        formData.append(key, data[key])
      }
      return formData
    },

    async handleCreate () {
      const formData = this.generateFormData()
      const { success, data } = await create(formData)
      if (success) {
        this.$Message.success(this.$t('devicesCreate.devCreateS'))
        this.ifUpdateUpper = true
        this.$_modal_close()
      } else {
        this.$Message.error(data)
      }
    },
    async handleUpdate () {
      if(!this.formData.photo){
        this.formData.photo=this.oldPhoto
      }
     
      
      const formData = this.generateFormData()
      // console.log(formData)
      const { success, data } = await update(formData)
      if (success) {
        this.$Message.success(this.$t('devicesCreate.devCreateUpdateS'))
        this.ifUpdateUpper = true
        this.$_modal_close()
      } else {
        this.$Message.error(data)
      }
    },
  },
}
</script>
<style lang="less" scoped>
/deep/ .ivu-date-picker-cells-header span{
  white-space: nowrap;
  font-size: 13px;
}
.alertTit{
  width: 90%;
  z-index: 10000;
  margin: 4px auto 20px;
  line-height: 14px;
}
</style>
